package com.region.loadbalancer.policy;

import com.region.loadbalancer.exception.ChooseServerException;
import com.region.loadbalancer.group.Server;
import com.region.loadbalancer.group.ServerState;

import java.util.List;

/**
 * Active/standby policy
 *
 * @author liujieyu
 * @date 2024/9/11 15:41
 * @desciption
 */
public class ActiveStandbyPolicy implements AllServerBalancerPolicy {

    private int masterIndex;

    public ActiveStandbyPolicy(int masterIndex) {
        this.masterIndex = masterIndex;
    }

    @Override
    public Server choose(List<Server> servers) {
        if (masterIndex < 0 || masterIndex >= servers.size()) {
            throw new ChooseServerException("The ActiveStandbyPolicy set default server index exceeds the total number of nodes.");
        }
        Server server = servers.get(masterIndex);
        if (ServerState.UP != server.getStatus()) {
            for (int i = 0; i < servers.size(); i++) {
                if (masterIndex == i) {
                    continue;
                }
                if (ServerState.UP == servers.get(i).getStatus()) {
                    server = servers.get(i);
                    break;
                }
            }
        }
        return server;
    }

    @Override
    public BalancerPolicy deepClone() {
        return new ActiveStandbyPolicy(masterIndex);
    }
}
